package main

import (
	"net/url"
	"os"

	"git.dev.tencent.com/lwch/runtime"
	"git.dev.tencent.com/lwch/torrent"
)

// PID peer id
var PID string

func init() {
	var err error
	PID, err = runtime.UUID(20)
	runtime.Assert(err)
}

func main() {
	// runtime.SetDebug(true) // only for test
	f, err := os.Open(os.Args[1])
	runtime.Assert(err)
	defer f.Close()
	var t torrent.Torrent
	runtime.Assert(torrent.NewFileDecoder(f).Decode(&t))

	// parse announces, not support udp yeat
	var announces []string
	announces = append(announces, t.Announce)
	for _, a := range t.AnnounceList {
		announces = append(announces, a)
	}
	infoHash, err := t.Info.Hash()
	runtime.Assert(err)
	runtime.Log("info_hash: %x", infoHash)
	runtime.Log("pieces: %d, length: %d", len(t.Info.Pieces), t.Info.PieceLength)
	for _, a := range announces {
		// if a != "http://tracker.torrentyorg.pl/announce" { // only for test
		// 	continue
		// }
		u, err := url.Parse(a)
		runtime.Assert(err)
		if u.Scheme != "http" && u.Scheme != "https" {
			// runtime.Log("%s is not http and https tracker skiped", a) // TODO: support udp
			continue
		}
		track := newTracker(a, infoHash, t.Info.Length)
		go p2p(t, track)
		// runtime.Log("request tracker %s failed", a)
	}
	download(t)
	<-make(chan int)
}
